package com.thx.file.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.CurdAction;
import com.thx.file.model.File;
import com.thx.file.service.FileManager;
import com.thx.file.util.WebFileUtil;

@Namespace("/upload")
@Action(value = "upload", results={
		@Result(name="uploadPath", location="/pages/system/stream/streamUpload.jsp")
})
@Controller
@Scope("prototype")
public class UploadAction extends CurdAction<File> {
	private static final long serialVersionUID = 6625749424673034439L;

	@Autowired
	private FileManager fileManager ;
	public void delFile(){
		try {
			String fileId = getRequest().getParameter("fileId").toString();
			boolean isDel = WebFileUtil.deleteFile(fileId);
			if(isDel){
				getResponse().getWriter().write("1");;//删除成功返回1
			}else{
				getResponse().getWriter().write("0");// 删除不成功返回0
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.debug("UploadAction中delFile删除文件出错",e);
		}
	}
	public void getFile(){
		try {
			getResponse().setCharacterEncoding("UTF-8");
			getResponse().setContentType("text/html;charset=UTF-8");
			String fileId = getRequest().getParameter("fileId").toString();
			PrintWriter out = getResponse().getWriter();
			JSONArray result = new JSONArray();
			String fileIdArray[] = fileId.split(",");
			for(int i=0;i<fileIdArray.length;i++){
				File file = WebFileUtil.getFileById(fileIdArray[i]);
			    if(file!=null){
					File tempFile = new File();
					tempFile.setFileId(file.getFileId());
					tempFile.setOldName(file.getOldName());
					result.put(new JSONObject(tempFile));
				}
			}
			String outText = URLDecoder.decode(result.toString(),"utf-8"); //解决乱码
            out.print(outText);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    public String toUploadPage(){
    	return "uploadPath";
    }
}
